﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace MqttClientDemo
{
    public partial class Form1 : Form
    {
        MqttClient client;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            string brokerHostName = "gzhwedu.cn";
            int brokerPort = 1883;
            string clientId = txtNodeName.Text;
            //string username = "develop";
            //string password = "666666";
            string[] topic = { "action/+/" + clientId + "/#"};
            byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE};
            //string caPath = "C:/MqttSSL/ca.crt";
            //X509Certificate caCert = new X509Certificate(caPath);
            //Console.WriteLine(caCert.ToString(true) + "\n" + caCert.ToString());
            //Console.ReadKey();
            //Console.WriteLine("------------------------分割线-------------------------------");
            //无SSL连接
            try
            {
                client = new MqttClient(brokerHostName, brokerPort, false, null, null, MqttSslProtocols.None);
                //单向SSL通信
                //MqttClient client = new MqttClient(brokerHostName, brokerPort, true, caCert, null, MqttSslProtocols.TLSv1_2, new RemoteCertificateValidationCallback(cafileValidCallback));
                //消息接受
                client.MqttMsgPublishReceived += new MqttClient.MqttMsgPublishEventHandler(messageReceive);
                //连接Broker
                client.Connect(clientId);
                Log("连接成功!");
                //client.Connect(clientId, username, password);

                client.Subscribe(topic, qosLevels);
            }
            catch (System.Exception)
            {
                Log("连接失败!");
            }
        }

        private void switchLight()
        {
            if (picLight.BackColor == Color.Green)
                picLight.BackColor = Color.Black;
            else
                picLight.BackColor = Color.Green;
        }

        void messageReceive(object sender, MqttMsgPublishEventArgs e)
        {
            //string msg = "Topic:" + e.Topic + "   Message:" + System.Text.Encoding.Default.GetString(e.Message);
            Log("Topic:" + e.Topic);
            string NodeName = txtNodeName.Text;
            if (e.Topic == "action/on/" + NodeName + "/blink")
            {
                switchLight();
                client.Publish("status/on", Encoding.ASCII.GetBytes(NodeName + "/blink"));
            }
            else if (e.Topic == "action/off/" + NodeName + "/wol")
            {
                Wakeup(e.Message);
                client.Publish("status/on", Encoding.ASCII.GetBytes(NodeName + "/wol"));
            }
        }

        private void Wakeup(byte[] message)
        {
            Log("Waking Up: " + Utils.Mac2String(message));
            try
            {
                IPAddress broadIp;
                if (string.IsNullOrEmpty(txtBroadIp.Text))
                    broadIp = IPAddress.Broadcast;
                else
                    broadIp = IPAddress.Parse(txtBroadIp.Text);
                Utils.WakeUp(message, broadIp);
            }
            catch(Exception ex)
            {
                Log(ex.Message);
            }
        }

        void Log(string message)
        {
            lbMsg.Items.Add(message);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (client != null)
                client.Disconnect();

        }
    }
}
